import React, { Component } from 'react'
import router from 'umi/router';
import { withRouter } from 'react-router-dom';
import { formatMessage } from 'umi-plugin-locale';
import HebPlayerPort from './hebPlayerLoader';
import BizIcon from '@/components/BizIcon'
import Battery from '@/components/Battery'
import styles from './index.less'
import { Modal, message } from 'antd';
import { hasFullScreenElement, setFullScreen, exitFullScreen } from '@/utils/utils'
import { ContextMenu, MenuItem, ContextMenuTrigger } from "react-contextmenu";

class VideoPlayer extends Component {

    state = {
        message: formatMessage({ id: 'liveVideo.video_loading' }),
        isPlay: false,
        encoding: '',
        bitRate: '0kbps',
        receive: 0,
        lost: 0,
        resolution: '0x0',
        fps: 0,
        battery: 0,
        muted: true,
        talkbacked: false,
        isFullScreen: false,
        showTools: false
    }
    constructor(props) {
        super(props);
        this.videoDiv = React.createRef();
    }

    componentDidMount() {
        if (this.props.device.gbId !== undefined && this.props.device.gbId !== '') {
            this.playVideo()
        }
    }

    componentWillUnmount() {
        HebPlayerPort.stopVideo(this.props.device.gbId);
        this.timer = null;
    }

    onPlay() {
        this.playVideo()
        this.setState({
            message: formatMessage({ id: 'liveVideo.video_loading' }),
        })
    }

    onStop() {
        HebPlayerPort.stopVideo(this.props.device.gbId);
        this.setState({
            isPlay: false,
            message: formatMessage({ id: 'liveVideo.pause' }),
        })
    }

    togglePlay() {
        !this.state.isPlay ? this.onPlay() : this.onStop()
    }

    playVideo() {
        let ret = HebPlayerPort.playVideo2(this.props.device.gbId, this.videoDiv.current, (type, a, b, c, d, e) => {
            if (type === 'metaData') {
                this.setState({
                    encoding: a,
                    resolution: b,
                    isPlay: true
                })
            } else if (type === 'dynamicInfo') {
                this.setState({
                    bitRate: a + 'kbps',
                    receive: b,
                    lost: c,
                    fps: d + 'fps',
                    isPlay: true
                })
            } else if (type === 'broken') {
                this.setState({
                    message: formatMessage({ id: 'liveVideo.broken' }),
                    isPlay: false
                })
            } else if (type === 'offline') {
                this.setState({
                    message: formatMessage({ id: 'liveVideo.offline' }),
                    isPlay: false
                })
            } else if (type === 'stopped') {
                let delVideoTimer = null
                if (a === "subForceStop") {
                    message.warning(formatMessage({ id: 'liveVideo.force_stop' }))
                    window.clearTimeout(delVideoTimer)
                    delVideoTimer = setTimeout(() => {
                        this.props.deletePlayer(this.props.device.gbId);
                    }, 3000)
                    this.setState({
                        message: formatMessage({ id: 'liveVideo.force_stop' }),
                        isPlay: false
                    })
                } else if (a === "noPermission") {
                    this.setState({
                        message: formatMessage({ id: 'liveVideo.forbidden' }),
                        isPlay: false
                    })
                } else if (a === "moreThanMaxPlayCount") {
                    Modal.warning({
                        title: formatMessage({ id: 'liveVideo.moreThanMaxPlayCount' }),
                        content: formatMessage({ id: 'liveVideo.moreThanMaxPlayCount.content' })
                    })
                    this.setState({
                        message: formatMessage({ id: 'liveVideo.moreThanMaxPlayCount' }),
                        isPlay: false
                    })
                }
            }
        });
        if (HebPlayerPort.isErrorStr(ret)) {
            console.log("fail to play %s", ret);
            return;
        }
    }

    onClose() {
        this.props.deletePlayer(this.props.device.gbId);
    }

    onMuted() {
        HebPlayerPort.setMuted(this.props.device.gbId, !this.state.muted);
        this.setState({
            muted: !this.state.muted
        })
    }

    onTalkback() {

        if (window.loadPlugin !== true) {
            Modal.confirm({
                title: formatMessage({ 'id': 'liveVideo.plugin_check_title' }),
                content: formatMessage({ 'id': 'liveVideo.plugin_check_description' }),
                centered: true,
                okText: formatMessage({ 'id': 'common.button.download' }),
                cancelText: formatMessage({ 'id': 'common.button.cancel' }),
                onOk() {
                    window.location.href = window.videoJsapiUrl + '/zbkAudioPlugin.zip';
                }
            });
        } else {
            if (!this.state.isPlay) {
                Modal.error({
                    title: formatMessage({ id: 'liveVideo.not_talkback' }),
                    centered: true
                })
            } else {
                HebPlayerPort.setTalkback(this.props.device.gbId, !this.state.talkbacked);
                this.setState({
                    talkbacked: !this.state.talkbacked
                })
            }
        }

    }

    dateFormat = (fmt, date) => {
        let ret;
        const opt = {
            "Y+": date.getFullYear().toString(),        // 年
            "m+": (date.getMonth() + 1).toString(),     // 月
            "d+": date.getDate().toString(),            // 日
            "H+": date.getHours().toString(),           // 时
            "M+": date.getMinutes().toString(),         // 分
            "S+": date.getSeconds().toString()          // 秒
        };
        for (const k in opt) {
            ret = new RegExp("(" + k + ")").exec(fmt);
            if (ret) {
                fmt = fmt.replace(ret[1], (ret[1].length === 1) ? (opt[k]) : (opt[k].padStart(ret[1].length, "0")));
            };
        };
        return fmt;
    }
    onScreenshot() {
        if (!this.state.isPlay) {
            Modal.error({
                title: formatMessage({ id: 'liveVideo.not_screenshot' }),
                centered: true
            })
        } else {
            const video = this.videoDiv.current.querySelector('video')
            const canvas = document.createElement('canvas');
            canvas.width = video.videoWidth;
            canvas.height = video.videoHeight;
            canvas.getContext('2d').drawImage(video, 0, 0, canvas.width, canvas.height);

            let dataURL;
            canvas.toBlob((blob) => {
                const fileName = this.dateFormat('YYYYmmddHHMMSS', new Date());
                dataURL = URL.createObjectURL(blob);
                const link = document.createElement('a');
                link.href = dataURL;
                link.download = fileName + '.png';
                link.style.display = 'none';
                document.body.appendChild(link);
                link.click();
                document.body.removeChild(link);
                URL.revokeObjectURL(dataURL);
            });
        }
    }

    onFullScreen() {
        if (this.state.isPlay) {
            if (hasFullScreenElement()) {
                exitFullScreen()
            } else {
                setFullScreen(this.videoView);
            }
            this.setState({ isFullScreen: !this.state.isFullScreen })
        }
    }

    onLocation() {
        const { id, sn } = this.props.device
        router.push({
            pathname: '/location',
            query: { id, sn }
        })
    }

    timer = null
    mouseMove() {
        this.setState({ showTools: true })
        clearTimeout(this.timer)
        this.timer = setTimeout(() => {
            this.setState({ showTools: false })
        }, 3000)
    }

    render() {
        return (
            <div
                ref={node => this.videoView = node}
                className={`${styles.player} ${this.state.showTools === true ? styles.move : ''}`}
                gbid={this.props.device.gbId}
                onMouseMove={this.mouseMove.bind(this)}
            >
                <div className={styles.head}>
                    <div className={`flex-item ${styles.title}`}>
                        <div className='flex-item'>
                            <span className={styles.realname}>
                                {this.props.device.realname || 'Unkown'}
                            </span>
                            {/* <span className={styles.gbId}>
                                [{this.props.device.gbId || 'Unkown'}]
                            </span> */}
                        </div>
                        {/* <div>
                            <Battery percent={this.props.device.power || 0} color='#ffffff' />
                        </div> */}
                    </div>
                    {/* <div className={styles.meta}>
                        {
                            this.state.isPlay === true && (
                                <div className={styles.videoInfo}>
                                    <span>{formatMessage({ id: 'player.code' })}: {this.state.encoding}</span>
                                    <span>{formatMessage({ id: 'player.bit_rate' })}: {this.state.bitRate}</span>
                                    <span>{formatMessage({ id: 'player.frame_rate' })}: {this.state.fps}</span>
                                    <span>{formatMessage({ id: 'player.resolution' })}: {this.state.resolution}</span>
                                </div>
                            )
                        }
                    </div> */}

                </div>
                <div className={styles.video} onDoubleClick={this.onFullScreen.bind(this)}>
                    <div className={styles.videoLoading} ref='noVideo'>
                        <div>
                            {
                                this.props.device.gbId ?
                                    this.state.message
                                    : formatMessage({ id: 'device.gbidIsNull' })
                            }
                        </div>
                    </div>
                    <ContextMenuTrigger id={`gbId-${this.props.device.gbId}`}>
                        <div ref={this.videoDiv} style={{ position: 'absolute', width: '100%', height: '100%' }} ></div>
                    </ContextMenuTrigger>
                </div>
                {
                    this.state.isPlay === true && (
                        <div className={styles.tool}>
                            <div onClick={this.onTalkback.bind(this)} className={this.state.talkbacked ? styles.active : ''}>
                                {
                                    !this.state.talkbacked ? <BizIcon type="icon-talkback" className={styles.toolIcon} />
                                        : <BizIcon type="icon-un-talkback" className={styles.toolIcon} />
                                }
                                <span>{formatMessage({ id: 'player.talkback' })}</span>
                            </div>
                            <div onClick={this.onMuted.bind(this)} className={this.state.muted ? styles.active : ''}>
                                {
                                    this.state.muted ? <BizIcon type="icon-muted" className={styles.toolIcon} />
                                        : <BizIcon type="icon-volume" className={styles.toolIcon} />
                                }
                                <span>{formatMessage({ id: 'player.mute' })}</span>
                            </div>
                            <div onClick={this.onLocation.bind(this)}>
                                <BizIcon type="icon-location" className={styles.toolIcon} />
                                <span>{formatMessage({ id: 'player.location' })}</span>
                            </div>
                            <div onClick={this.onScreenshot.bind(this)}>
                                <BizIcon type="icon-cut" className={styles.toolIcon} />
                                <span>{formatMessage({ id: 'player.cut' })}</span>
                            </div>
                            {
                                this.state.isPlay === true ? (
                                    <div onClick={this.onStop.bind(this)}>
                                        <BizIcon type="icon-stop" className={styles.toolIcon} />
                                        <span>{formatMessage({ id: 'player.stop' })}</span>
                                    </div>
                                ) : (
                                    <div onClick={this.onPlay.bind(this)}>
                                        <BizIcon type="icon-play" className={styles.toolIcon} />
                                        <span>{formatMessage({ id: 'player.play' })}</span>
                                    </div>
                                )
                            }
                            <div onClick={this.onFullScreen.bind(this)}>
                                <BizIcon type="icon-fullscreen" className={styles.toolIcon} />
                                <span>
                                    {
                                        this.state.isFullScreen ? formatMessage({ id: 'player.exit_fullscreen' }) : formatMessage({ id: 'player.fullscreen' })
                                    }
                                </span>
                            </div>

                        </div>
                    )
                }

                <ContextMenu id={`gbId-${this.props.device.gbId}`}>
                    <MenuItem onClick={this.togglePlay.bind(this)}>{!this.state.isPlay ? formatMessage({ id: 'player.play' }) : formatMessage({ id: 'player.stop' })}</MenuItem>
                    <MenuItem divider />
                    <MenuItem onClick={this.onLocation.bind(this)}>{formatMessage({ id: 'player.location' })}</MenuItem>
                    <MenuItem onClick={this.onScreenshot.bind(this)}>{formatMessage({ id: 'player.cut' })}</MenuItem>
                    <MenuItem divider />
                    <MenuItem onClick={this.onClose.bind(this)}>{formatMessage({ id: 'player.close' })}</MenuItem>
                    <MenuItem onClick={this.onFullScreen.bind(this)}>
                        {
                            this.state.isFullScreen ? formatMessage({ id: 'player.exit_fullscreen' }) : formatMessage({ id: 'player.fullscreen' })
                        }
                    </MenuItem>
                </ContextMenu>
            </div>
        )
    }
}
export default withRouter(VideoPlayer)
